//
//  PostsViewController.m
//  iWeddingDirectory
//
//  Created by Tung Ngo on 5/30/12.
//  Copyright (c) 2012 Home. All rights reserved.
//

#import "PostsViewController.h"
#import "API.h"
#import "Post.h"
#import "PostViewController.h"
#import "SendInquiryViewController.h"
#import "LoginViewController.h"


@implementation PostsViewController

@synthesize category;
@synthesize posts;
@synthesize buttonInquiryToAll;
@synthesize buttonCancel;
@synthesize inquiryMode;
@synthesize ids;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    [category release];
    [posts release];
    [buttonInquiryToAll release];
    [buttonCancel release];
    [ids release];
    [super dealloc];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
    
    self.title = @"Suppliers";
    
    buttonInquiryToAll = [[UIBarButtonItem alloc] initWithTitle:@"Inquiry To All" style:UIBarButtonItemStyleDone target:self action:@selector(onButtonInquiryToAllClicked:)];
    self.navigationItem.rightBarButtonItem = buttonInquiryToAll;
    
    buttonCancel = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleDone target:self action:@selector(onButtonCancelClicked:)];
    
    ids = [[NSMutableArray alloc] initWithCapacity:0];
    
    posts = [[NSMutableArray alloc] initWithCapacity:0];
    
    UIActivityIndicatorView *waitingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [waitingIndicator setTag:1000];
    [waitingIndicator setCenter:CGPointMake(160, 181)];
    [self.view addSubview:waitingIndicator];
    [waitingIndicator startAnimating];
    [waitingIndicator release];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPostsReceived:) name:kPostsReceivedNotification object:nil];
    API *api = [API sharedInstance];
    [api getPostsInCategoryWithId:category.categoryId];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [posts count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    Post *post = [posts objectAtIndex:indexPath.row];
    cell.textLabel.text = post.title;
    if( inquiryMode ) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [ids addObject:[NSNumber numberWithInt:post.postId]];
    }
    else
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (inquiryMode) {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        Post *post = [posts objectAtIndex:indexPath.row];
        if ([ids containsObject:[NSNumber numberWithInt:post.postId]]) {
            [ids removeObject:[NSNumber numberWithInt:post.postId]];
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        else {
            [ids addObject:[NSNumber numberWithInt:post.postId]];
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        if ([ids count] > 0) {
            buttonInquiryToAll.title = @"Send Inquiry";
        }
        else {
            buttonInquiryToAll.title = @"Inquiry To All";
        }
    } 
    else 
    {
        /*
        PostViewController *vcPost = [[PostViewController alloc] init];
        Post *post = [posts objectAtIndex:indexPath.row];
        [vcPost setPost:post];
        [vcPost setPostType:REMOTE_POST];
        [self.navigationController pushViewController:vcPost animated:YES];
        [vcPost release];
        */

        BusinessProfileCtrl* businessCtrl = [[BusinessProfileCtrl alloc] init];
        Post *post = [posts objectAtIndex:indexPath.row];
        [businessCtrl setPost:post];
        [businessCtrl setPostType:REMOTE_POST];
        [self.navigationController pushViewController:businessCtrl animated:YES];
        [businessCtrl release];
        
    }
}

#pragma mark - Posts received notification

- (void)onPostsReceived:(NSNotification *)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kPostsReceivedNotification object:nil];
    
    UIActivityIndicatorView *waitingIndicator = (UIActivityIndicatorView *)[self.view viewWithTag:1000];
    [waitingIndicator stopAnimating];
    
    NSDictionary *result = [notification userInfo];
    NSLog(@"result = %@", result);
    NSArray *_posts = [result objectForKey:@"posts"];
    for (NSDictionary *_post in _posts) {
        Post *post = [[Post alloc] init];
        int postId = [[_post objectForKey:@"id"] intValue];
        NSString *title = [_post objectForKey:@"title"];
        post.postId = postId;
        post.title = title;
        [posts addObject:post];
        [post release];
    }
    [self.tableView reloadData];
}

#pragma mark - Button Clicked Handlers

- (void)onButtonCancelClicked:(id)sender
{
    self.navigationItem.leftBarButtonItem = nil;
    inquiryMode = NO;
    [ids removeAllObjects];
    [self.tableView reloadData];
}

- (void)onButtonInquiryToAllClicked:(id)sender
{
    
    buttonInquiryToAll.title = @"Send Inquiry";

    NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];

    if( username != nil ){
        self.navigationItem.leftBarButtonItem = buttonCancel;
        if (inquiryMode == NO || ( inquiryMode == YES && [ids count] == 0) ) {
            inquiryMode = YES;
            [self.tableView reloadData];
        }
        else if ([ids count] > 0) {
            NSString *_ids = [ids componentsJoinedByString:@","];
            SendInquiryViewController *vcSendInquiry = [[SendInquiryViewController alloc] init];
            vcSendInquiry.ids = _ids;
            [self.navigationController pushViewController:vcSendInquiry animated:YES];
            [vcSendInquiry release];
        }
    } else {
        UIAlertView *alv = [[UIAlertView alloc] initWithTitle:@"iWeddingDirectory" message:@"Please login to send the message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Not now", nil];
        [alv show];
        [alv release];
    }
}

#pragma mark - alerview delegate

-(void) alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if( buttonIndex == 0 ){//OK
        LoginViewController * login = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
        [self.navigationController pushViewController:login animated:YES];
        [[NSUserDefaults standardUserDefaults] setValue:@"yes" forKey:@"push_back"];
        [login release];
                                    
    } else {
        //Do nothing
    }
}

@end
